package com.andybest.search.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.logging.Log;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import com.andybest.search.dto.ItemDto;
import com.andybest.search.dto.TaskInfo;

public class ExcuteTask {

	private static Logger log = Logger.getLogger(ExcuteTask.class);

	public static final String DEVELOPER_ID_RAKUTEN = "176d0973c7e98cfd730d3783d2690953";

	public static final String DEVELOPER_ID_YAHOO = "";

	public static final String DEVELOPER_ID_KAKAKU = "";

	public static final String HOST_RAKUTEN = "api.rakuten.co.jp";
	public static final String SEARCH_URL_RAKUTEN = "/rws/3.0/rest?";

	public static final String SEARCH_VERSION_RAKUTEN = "2010-09-15";

	public static final String SEARCH_TYPE_RAKUTEN = "R";

	public static final String SEARCH_TYPE_YAHOO = "Y";

	public static final String SEARCH_TYPE_KAKAKU = "K";

	public static ItemDto doExcuteTask(TaskInfo taskInfo) {
		ItemDto itemDto =null;
		if (SEARCH_TYPE_RAKUTEN.equals(taskInfo.getSearchType().toUpperCase())) {
			try {
				itemDto = doExcuteTaskRakuten(taskInfo);
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO 自動生成された catch ブロック
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO 自動生成された catch ブロック
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO 自動生成された catch ブロック
				e.printStackTrace();
			}
		} else if (SEARCH_TYPE_YAHOO.equals(taskInfo.getSearchType()
				.toUpperCase())) {

		} else if (SEARCH_TYPE_KAKAKU.equals(taskInfo.getSearchType()
				.toUpperCase())) {

		} else {

		}
		return itemDto;
	}

	private static ItemDto doExcuteTaskRakuten(TaskInfo taskInfo) throws ClientProtocolException, IllegalStateException, IOException, SAXException, ParserConfigurationException {
		// http://api.rakuten.co.jp/rws/3.0/rest?developerId=176d0973c7e98cfd730d3783d2690953&operation=ItemSearch&version=2010-09-15&keyword=%E7%A6%8F%E8%A2%8B&sort=%2BitemPrice
		String searchUrl = "";
		try {
			searchUrl = SEARCH_URL_RAKUTEN
					+ "developerId="
					+ DEVELOPER_ID_RAKUTEN //
					+ "&" + "operation="
					+ "ItemSearch" //
					+ "&" + "version="
					+ SEARCH_VERSION_RAKUTEN //
					+ "&" + "sort="
					+ "%2BitemPrice" //
					+ "&" + "hits="
					+ "5" //
					+ "&" + "field="
					+ "1" //
					+ "&" + "keyword="
					+ URLEncoder.encode(taskInfo.getItemName(), "UTF-8");
			if (taskInfo.getCategoryId() != null
					&& !taskInfo.getCategoryId().equals("")) {
				searchUrl += "&" + "genreId=" + taskInfo.getCategoryId();
			}

			if (taskInfo.getNgKeyword() != null
					&& !taskInfo.getNgKeyword().equals("")) {
				searchUrl += "&" + "NGKeyword="
						+ URLEncoder.encode(taskInfo.getNgKeyword(), "UTF-8");
			}
			if (taskInfo.getMinPrice()>0) {
				searchUrl += "&" + "minPrice="
						+ taskInfo.getMinPrice();
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		System.out.println(searchUrl);
		return searchRakuten(searchUrl);
	}

	private static ItemDto searchRakuten(String searchUrl)
			throws ClientProtocolException, IOException, IllegalStateException,
			SAXException, ParserConfigurationException {
		ItemDto itemDto =null;
		DefaultHttpClient httpclient = new DefaultHttpClient();
		 // TODO
		 HttpHost proxy = new HttpHost("proxysv", 80);
		 httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
		 proxy);
		 httpclient.getCredentialsProvider().setCredentials(
		 AuthScope.ANY,
		 new NTCredentials("ts-ming.liu", "R@kuten1234", "proxysv",
		 "intra.rakuten.co.jp"));
//		 TODO

		HttpHost targetHost = new HttpHost(HOST_RAKUTEN, 80, "http");
		HttpGet httpget = new HttpGet(searchUrl);
		HttpResponse response = httpclient.execute(targetHost, httpget);

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.parse(response.getEntity().getContent(), "UTF-8");
		String status =doc.getElementsByTagName("Status").item(0).getTextContent();
		System.out.println(status);
		if(status.equals("Success")){
			Node itemNode =doc.getElementsByTagName("Item").item(0);
			String itemName =itemNode.getChildNodes().item(0).getTextContent();
			String itemCode =itemNode.getChildNodes().item(2).getTextContent();
			String itemPrice =itemNode.getChildNodes().item(3).getTextContent();
			String itemUrl =itemNode.getChildNodes().item(5).getTextContent();

			itemDto = new ItemDto();
			itemDto.setItemCode(itemCode);
			itemDto.setItemName(itemName);
			itemDto.setItemPrice(Long.parseLong(itemPrice));
			itemDto.setItemUrl(itemUrl);
		}
		httpclient.getConnectionManager().shutdown();
		return itemDto;
	}

	public static void main(String[] args) {
		TaskInfo taskInfo = new TaskInfo();
		taskInfo.setItemName("放射線測定器");
		taskInfo.setSearchType("R");
		// taskInfo.setCategoryId("100040");
		taskInfo.setNgKeyword("フィルム case ケース");
		doExcuteTask(taskInfo);
	}
}
